package dhy.com.container;


import dhy.com.anno.Client;
import dhy.com.anno.EnableRpcMain;
import dhy.com.anno.Server;
import dhy.com.exception.RpcContainerException;
import org.reflections.Reflections;
import org.reflections.scanners.*;

import java.util.Arrays;
import java.util.Set;

/**
  *容器实例扫描类
 * @author zdh
 */
public class RpcContainerScanner {
    /**
     * 扫描工具类
     */
    private final Reflections reflections;

    /**
     * rpc容器类
     */
    private final RpcContainerImpl rpcContainer;

    public RpcContainerScanner(RpcContainerImpl rpcContainer) throws RpcContainerException {
        reflections=new Reflections(
                "",
                Arrays.asList(
                        new SubTypesScanner(false)
                        ,new MethodParameterNamesScanner()
                        ,new MethodAnnotationsScanner()
                        ,new MemberUsageScanner()
                        ,new TypeAnnotationsScanner()
                )
        );
        this.rpcContainer=rpcContainer;
    }

    /**
     * 扫描包下面的加了Cilent注解的接口类,然后加入client容器集合中保存
     */
    final public void scannerClient()
    {
        Set<Class<?>> classSet = reflections.getTypesAnnotatedWith(Client.class);
        classSet.stream().forEach(c-> {
            try {
                rpcContainer.putInstanceIntoClient(c);
            } catch (RpcContainerException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 扫描包下面的Server注解
     */
    final public void  scannerServer()
    {
        Set<Class<?>> classSet = reflections.getTypesAnnotatedWith(Server.class);
        classSet.stream().forEach(c-> {
            try {
                rpcContainer.putInstanceIntoServer(c);
            } catch (RpcContainerException e) {
                e.printStackTrace();
            }
        });
    }



    /**
     *  <P>
     *      是否开启远程调用服务
     *  </P>
     */
    public boolean isEnableRpcServer(){
        Set<Class<?>> classes = reflections.getTypesAnnotatedWith(EnableRpcMain.class);
        if(classes.size()==0)
        {
            return false;
        }
        return true;
    }
}
